import threading
import random
import time
gLock = threading.Lock() #因为要操作共享变量 所以记得上锁
gMoney = 1000
gTotalTime = 10
gTime = 0 #生产一次 次数+1 消费一次 都加1
#生产者
class ProducerThread(threading.Thread):
    def run(self):
        global gMoney
        global gTime
        while True:
            money = random.randint(100,999)
            gLock.acquire()

            if gTime >= gTotalTime:
                gLock.release()
                break
            gMoney += money
            print("%s生产了%d元钱,余额为%d元钱" % (threading.current_thread(),money,gMoney))
            gTime += 1
            gLock.release()
            time.sleep(1)

#消费者
class CustomerThread(threading.Thread):
    def run(self):
        global gMoney
        while True:
            money = random.randint(100,999)
            gLock.acquire()
            if gMoney >= money:
               gMoney -= money
               print("%s消费了%d元钱,余额为%d元钱" % (threading.current_thread(), money, gMoney))
            else:
                if gTime>= gTotalTime:
                    gLock.release()
                    break  #虽然break 但是没有释放锁 导致 锁一直在等待
                print("%s准备消费%d元钱,余额为%d元钱,余额不足" % (threading.current_thread(), money, gMoney))
            gLock.release()
            time.sleep(1)

def main():
    for x in range(3):
        t = CustomerThread()
        t.start()
    for x in range(5):
        t = ProducerThread()
        t.start()

if __name__ == '__main__':
    main()